﻿using Haidou.Wpf.UI.Util;
using Haidou.Wpf.Util;
using Haidou.Wpf.Util.Settings;
using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Window = System.Windows.Window;
using WF = System.Windows.Forms; // added alias

namespace Haidou.Wpf.UI.Windows
{
	/// <summary>
	/// Options.xaml 的交互逻辑
	/// </summary>
	public partial class Options : Window
	{
		public Options()
		{
			InitializeComponent();
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{

		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{

			////项目属性- 包-常规-程序集版本 本地版本
			Version? AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version;
			SystemversionnumberText.Text = $"{AssemblyVersion}";
			string Is64BitOperatingSystems = "32";
			string Is64BitProcess = "32";

			if (Arguments.Is64BitOperatingSystem)
			{
				Is64BitOperatingSystems = "64";
			}
			if (Arguments.Is64BitProcess)
			{
				Is64BitProcess = "64";

			}

			Is64BitOperatingSystem.Text = $"您系统的位数:{Is64BitOperatingSystems},软件运行的位数：{Is64BitProcess}";

			ProcessingResolution();


		}

		/// <summary>
		/// 处理分辨率
		/// </summary>
		public void ProcessingResolution()
		{
			int pHeight = WF.Screen.PrimaryScreen.Bounds.Height; //1080
			int pWidth = WF.Screen.PrimaryScreen.Bounds.Width; //1920

			//var scale = GetScreenScale();

			double dpiScaleX = VisualTreeHelper.GetDpi(this).DpiScaleX;

			//Debug.WriteLine(pWidth);
			if (pHeight >= 1080 && pWidth >= 1920 && dpiScaleX == 1)
			{
				Debug.WriteLine(pWidth);
			}
			else if (dpiScaleX != 1)
			{
				Width = 920;
				Height = 652;
				Top = 30;
			}
			else
			{
				this.WindowStartupLocation = WindowStartupLocation.CenterOwner;

				Width = 710;
				Height = 551;
				Top = 50;

			}



		}

		private void ToggleButton_Checked(object sender, RoutedEventArgs e)
		{
			if (DelineationTranslation_Btn.IsChecked == true)
			{
				App_Startup.SetMeAutoStart(true);

				//保存本地配置项
				UserSettings.All.Startup = true;
				UserSettings.Save();
			}
			else
			{
				App_Startup.SetMeAutoStart(false);


				//保存本地配置项
				UserSettings.All.Startup = false;
				UserSettings.Save();
			}
		}

		private void DelineationTranslation_Btn_Unchecked(object sender, RoutedEventArgs e)
		{

		}

		private void CurrentlanguageComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{

		}

		private void clearBtn_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				Growl.AskGlobal("您要清除缓存文件夹吗？" + "使用时或您进行设置、日志文件、数据缓存等，将创建一个项目并将其存储在缓存文件夹中。", isConfirmed =>
				{
					if (isConfirmed)
					{
						string documents = string.IsNullOrWhiteSpace(UserSettings.All.LogsFolder) ? Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) : UserSettings.All.LogsFolder;

						string directoryPath = System.IO.Path.Combine(documents, "AYDTikTokData");
						LogWriter.DeleteDirectory(directoryPath);
						UserSettings.RemoveAppDataSettings();

						//Cef.GetGlobalCookieManager().DeleteCookies(null, null, null);
						string cachePath = AppDomain.CurrentDomain.BaseDirectory + "caches";
						if (Directory.Exists(cachePath))
						{
							try
							{
								Task.Delay(2000);

								// 2. 强制GC回收，确保所有文件句柄释放
								GC.Collect();
								GC.WaitForPendingFinalizers();

								Directory.Delete(cachePath, true);
								LogWriter.Log("caches 数据清除成功");



							}
							catch (Exception ex1)
							{
								LogWriter.Log(ex1, "clearBtn_Click cachePath可能被占用");
								Growl.InfoGlobal(" cachePath可能被占用。");

							}
						}

						try
						{

							string cachePathcef = AppDomain.CurrentDomain.BaseDirectory + "cef\\caches";
							if (Directory.Exists(cachePathcef))
							{
								try
								{
									// 释放所有CefSharp相关资源
								
									GC.Collect();
									GC.WaitForPendingFinalizers();

									foreach (var file in Directory.GetFiles(cachePathcef, "*", SearchOption.AllDirectories))
									{
										File.SetAttributes(file, FileAttributes.Normal);

									}
									Directory.Delete(cachePathcef, true);
									LogWriter.Log("cef\\caches 数据清除成功");
								}
								catch (Exception ex)
								{
									Debug.WriteLine(ex.Message);
								}
							}
						}
						catch (Exception)
						{

						}

						GC.Collect();
						GC.WaitForPendingFinalizers();


						//// 清除本地Sqlite comments.db
						//string dbPath = DatabaseConfig.SharedDbDirectory;
						//if (Directory.Exists(dbPath))
						//{
						//	try
						//	{
						//		Directory.Delete(dbPath, true);
						//		LogWriter.Log("本地评论数据库 SharedDbDirectory 已删除");
						//		Debug.WriteLine("本地评论数据库 SharedDbDirectory已删除");
						//	}
						//	catch (Exception ex2)
						//	{
						//		LogWriter.Log(ex2, "clearBtn_Click 删除comments.db");
						//		Growl.InfoGlobal("删除db出现了异常。");

						//	}
						//}


						Growl.SuccessGlobal("删除AppData设置成功。");

					}
					return true;

				});



			}
			catch (Exception ex)
			{
				//Dialog.Ok("Remove AppData Settings.删除AppData设置", "Impossible to remove AppData settings.无法删除AppData设置", ex.Message);
				LogWriter.Log(ex, "Remove AppData Settings.删除AppData设置");

			}
		}

		private void OpenLogs_Click(object sender, RoutedEventArgs e)
		{
			string local = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AYDTikTokData\\Logs\\");

			string folderPath = local; // 
			try
			{
				// 打开默认的文件浏览器窗口到指定文件夹
				Process.Start("explorer", folderPath);
			}
			catch (Exception ex)
			{
				Debug.WriteLine($"An error occurred: {ex.Message}"); // 输出错误信息到控制台
				LogWriter.Log(ex, ".OpenLogs_Click");

			}
		}

		private async void Checkforupdates_Click(object sender, RoutedEventArgs e)
		{

			//var isupdate = await AutoUpdate.Start();
			//if (!isupdate)
			//{
			//	Growl.ClearGlobal();
			//	// 已经是最新版本，无需更新
			//	Growl.InfoGlobal("已经是最新版本，无需更新。");
			//}

		}

		private void OpenDisclaimer_Click(object sender, RoutedEventArgs e)
		{
			try
			{
				var disclaimerPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resources", "disclaimer.txt");
				if (System.IO.File.Exists(disclaimerPath))
				{
					var text = System.IO.File.ReadAllText(disclaimerPath, System.Text.Encoding.UTF8);
					var win = new System.Windows.Window
					{
						Title = "用户协议",
						Width = 600,
						Height = 500,
						Owner = this, // 设为当前窗口为所有者
						WindowStartupLocation = WindowStartupLocation.CenterOwner, // 居中显示
						ShowInTaskbar = false,
						Content = new HandyControl.Controls.ScrollViewer
						{
							Content = new TextBlock
							{
								Text = text,
								TextWrapping = TextWrapping.Wrap,
								Margin = new Thickness(20)
							}
						}
					};
					win.ShowDialog();
				}
				else
				{
					HandyControl.Controls.MessageBox.Show("未找到用户协议文件！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
				}
			}
			catch (Exception ex)
			{
				HandyControl.Controls.MessageBox.Show("打开用户协议失败：" + ex.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		// ---- Window Chrome Handlers ----
		private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
		{
			if (e.ClickCount == 2)
			{
				BtnMax_Click(sender, e);
				return;
			}
			if (e.ButtonState == MouseButtonState.Pressed)
			{
				try { DragMove(); } catch { }
			}
		}

		private void BtnMin_Click(object sender, RoutedEventArgs e) => WindowState = WindowState.Minimized;

		private void BtnMax_Click(object sender, RoutedEventArgs e)
		{
			WindowState = WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized;
		}

		private void BtnClose_Click(object sender, RoutedEventArgs e) => Close();
	}
}
